#pragma once
#include "Log.hpp"
#include <sys/epoll.h>
#include <unistd.h>
class Epoll
{
    static const int size = 128;
    static const int defaultfd = -1;

public:
    Epoll() : _epollfd(defaultfd)
    {
    }
    ~Epoll()
    {
        if (_epollfd != defaultfd)
            close(_epollfd);
    }
    void Create()
    {
        _epollfd = epoll_create(size);
        if (_epollfd == -1)
        {
            logMessage(ERROR, "epoll_create fail : %s", strerror(errno));
            exit(EPOLL_CREATE_ERR);
        }
        logMessage(NORMAL, "epoll_create success");
    }
    bool Control(int fd, int op, uint32_t event)
    {
        if (op == EPOLL_CTL_ADD)
        {
            struct epoll_event ev;
            ev.data.fd = fd;
            ev.events = event;
            int ret = epoll_ctl(_epollfd, op, fd, &ev);
            if (ret == -1)
            {
                logMessage(ERROR, "epoll_ctl(ADD) fail : %s", strerror(errno));
                return false;
            }
        }
        else if (op == EPOLL_CTL_DEL)
        {
            int ret = epoll_ctl(_epollfd, op, fd, nullptr);
            if (ret == -1)
            {
                logMessage(ERROR, "epoll_ctl fail(DEL) : %s", strerror(errno));
                return false;
            }
        }
        else if (op == EPOLL_CTL_MOD)
        {
            struct epoll_event ev;
            ev.data.fd = fd;
            ev.events = event;
            int ret = epoll_ctl(_epollfd, op, fd, &ev);
            if (ret == -1)
            {
                logMessage(ERROR, "epoll_ctl fail(MOD) : %s", strerror(errno));
                return false;
            }
        }
        else
            return false;
        return true;
    }
    int Wait(int num, struct epoll_event *events)
    {
        int n = epoll_wait(_epollfd, events, num, -1);
        return n;
    }

private:
    int _epollfd;
};